package com.arpa.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.cache.PartyCache;
import com.arpa.ntocc.common.common.cache.PartyGroupCache;
import com.arpa.ntocc.common.common.cache.ShipmentCache;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.CommonUtil;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.wms.cache.GoodsCache;
import com.arpa.wms.cache.LocationCache;
import com.arpa.wms.cache.WarehouseCache;
import com.arpa.wms.common.util.OrderIdGeneratorUtil;
import com.arpa.wms.domain.dto.CountingDTO;
import com.arpa.wms.domain.dto.CountingItemDTO;
import com.arpa.wms.domain.dto.CountingRegisterDTO;
import com.arpa.wms.domain.entity.*;
import com.arpa.wms.domain.enums.*;
import com.arpa.wms.domain.vo.CountingItemVO;
import com.arpa.wms.domain.vo.CountingRegisterVO;
import com.arpa.wms.domain.vo.CountingVO;
import com.arpa.wms.mapper.CountingMapper;
import com.arpa.wms.mapper.WmsTaskMapper;
import com.arpa.wms.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 盘点单 服务实现类
 *
 * @author jinss
 * @date 2020-08-28 11:26:07
 **/
@Service
@Log4j2
public class CountingServiceImpl extends ServiceImpl<CountingMapper, Counting> implements ICountingService {

    private final ICountingItemService countingItemService;
    private final ICountingRegisterService countingRegisterService;
    private final WarehouseCache warehouseCache;
    private final PartyCache partyCache;
    private final ShipmentCache shipmentCache;
    private final IDifferenceService iDifferenceService;
    private final IDifferenceItemService iDifferenceItemService;
    private final GoodsCache goodsCache;
    private final LocationCache locationCache;
    private final IInventoryStatusService iInventoryStatusService;
    private final ILocationService iLocationService;

    @Resource
    private WmsTaskMapper wmsTaskMapper;
    @Autowired
    private PartyGroupCache partyGroupCache;
    @Autowired
    private IInventoryService inventoryService;
    @Autowired
    private IInventoryRecordService iInventoryRecordService;


    public CountingServiceImpl(ICountingRegisterService countingRegisterService,
                               ICountingItemService countingItemService,
                               WarehouseCache warehouseCache,
                               PartyCache partyCache,
                               IDifferenceService iDifferenceService,
                               IDifferenceItemService iDifferenceItemService,
                               IInventoryStatusService iInventoryStatusService,
                               GoodsCache goodsCache,
                               LocationCache locationCache, ShipmentCache shipmentCache, ILocationService iLocationService
    ) {
        this.countingRegisterService = countingRegisterService;
        this.countingItemService = countingItemService;
        this.warehouseCache = warehouseCache;
        this.partyCache = partyCache;
        this.iDifferenceService = iDifferenceService;
        this.iDifferenceItemService = iDifferenceItemService;
        this.goodsCache = goodsCache;
        this.locationCache = locationCache;
        this.iInventoryStatusService = iInventoryStatusService;
        this.shipmentCache = shipmentCache;
        this.iLocationService = iLocationService;
    }

    private boolean add(Counting entity) {
        entity.setCode(OrderIdGeneratorUtil.generatorOrderId(OrderIdGeneratorUtil.OrderTypeEnum.PD, "",UserUtil.getBranchCode()));
        entity.setWarehouseName(warehouseCache.translate(entity.getWarehouseCode()));
        entity.setCreatedBy(UserUtil.getCode());
        entity.setCreatedName(partyCache.translate(UserUtil.getCode()));
        entity.setModifiedBy(UserUtil.getCode());
        entity.setModifiedName(partyCache.translate(UserUtil.getCode()));
        entity.setGroupCode(UserUtil.getBranchCode());
        //保存明细
        this.saveItem(entity);
        return super.save(entity);
    }

    /**
     * 保存
     *
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean save(Counting entity) {
        return add(entity);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean submit(Counting counting) {
        // 生成盘点登记信息
        List<CountingItem> countingItemList = counting.getCountingItemList();
        if (CollUtil.isEmpty(countingItemList)) {
            throw new ServiceException("盘点登记明细为空，不可提交!");
        }
        counting.setStatus(CountingStatusEnum.WAIT_COUNT.getValue());
        boolean update = false;
        boolean add = false;
        if (StrUtil.isNotBlank(counting.getCode())) {
            //更新盘点信息，明细信息
            boolean countingUpdateResult = updateByCode(counting);
            boolean countingItemUpdateResult = countingItemService.update(new UpdateWrapper<CountingItem>().lambda()
                    .eq(CountingItem::getGroupCode,UserUtil.getBranchCode())
                    .eq(CountingItem::getCountingCode, counting.getCode())
                    .set(CountingItem::getStatus, CountingStatusEnum.WAIT_COUNT.getValue())
                    .set(CountingItem::getModifiedBy, UserUtil.getCode())
                    .set(CountingItem::getModifiedName, partyCache.translate(UserUtil.getCode()))
            );


            update = countingUpdateResult && countingItemUpdateResult;
        } else {
            //直接提交盘点单，盘点明细，
            add = this.add(counting);
        }
       /* List<CountingRegister> countingRegisterList = counting.getCountingItemList().stream().map(item -> {
            CountingRegister countingRegister = new CountingRegister();
            BeanUtils.copyProperties(item, countingRegister);
            countingRegister.setCode(IdUtil.simpleUUID());
            //登记类型：0普通(默认)，1补登"
            countingRegister.setRegisterType(0);
            countingRegister.setStatus(CountingStatusEnum.WAIT_COUNT.getValue());
            countingRegister.setCountingCode(counting.getCode());
            countingRegister.setCountingItemCode(item.getCode());
            countingRegister.setCreatedBy(UserUtil.getCode());
            countingRegister.setGmtCreated(LocalDateTime.now());
            countingRegister.setCountingQuantity(item.getCountingQuantity());
            countingRegister.setInventoryQuantity(item.getQuantity());
            return countingRegister;
        }).collect(Collectors.toList());*/
        //boolean countingRegisterResult = countingRegisterService.saveBatch(countingRegisterList);
        countingRegisterService.insertBatch(counting.getCode(),UserUtil.getCode());
        return update && add;
    }

    /**
     * 更新盘点单
     * 只更新监盘人和备注，不更新明细
     *
     * @param entity
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean updateByCode(Counting entity) {
        entity.setModifiedBy(UserUtil.getCode());
        entity.setModifiedName(partyCache.translate(UserUtil.getCode()));
        return super.update(entity, new UpdateWrapper<Counting>().lambda().eq(Counting::getCode, entity.getCode()).eq(Counting::getGroupCode,UserUtil.getBranchCode()));
    }

    public int update(Counting entity) {
        if (StrUtil.isBlank(entity.getModifiedBy())) {
            entity.setModifiedBy(UserUtil.getCode());
            entity.setModifiedName(partyCache.translate(UserUtil.getCode()));
        }
        //删除所有明细
        countingItemService.remove(new QueryWrapper<CountingItem>().lambda().eq(CountingItem::getCountingCode, entity.getCode()).eq(CountingItem::getGroupCode,UserUtil.getBranchCode()));
        //保存明细
        this.saveItem(entity);
        return baseMapper.update(entity, new QueryWrapper<Counting>().lambda().eq(Counting::getCode, entity.getCode()).eq(Counting::getGroupCode,UserUtil.getBranchCode()));
    }

    /**
     * 查询列表
     *
     * @param countingDTO
     * @return
     */
    @Override
    public List<CountingVO> queryList(CountingDTO countingDTO) {
        //排序字段名需要驼峰转数据库下划线类型字段名
        if (StrUtil.isNotEmpty(countingDTO.getSortField())) {
            countingDTO.setSortField(CommonUtil.camel2Underline(countingDTO.getSortField()));
        }
        List<CountingVO> countingVOList = baseMapper.queryList(countingDTO);

        return countingVOList;
    }

    @Override
    public List<String> queryByGoodsCode(List<String> list) {
        return baseMapper.queryByGoodsCode(list);
    }

    /**
     * 查询合计,包含总数
     *
     * @param countingDTO
     * @return
     */
    @Override
    public CountingVO queryListSum(CountingDTO countingDTO) {
        CountingVO countingVO = baseMapper.queryListSum(countingDTO);
        return countingVO;
    }

    @Override
    public CountingVO getOneByCode(String code,int pageNum,int pageSize, String groupCode) {
        Counting counting = getOne(new QueryWrapper<Counting>().lambda().eq(Counting::getCode, code).eq(Counting::getGroupCode,groupCode));
        if (null == counting) {
            log.error("盘点单【{}】不存在", code);
            throw new ServiceException("盘点单: " + code + "不存在!");
        }

        CountingVO countingVO = new CountingVO();
        BeanUtils.copyProperties(counting, countingVO);
        // 翻译
        if (StrUtil.isNotBlank(countingVO.getLocation())) {
            countingVO.setLocationName(locationCache.translate(countingVO.getLocation()));
        }
        if (StrUtil.isNotBlank(countingVO.getShipmentCode())) {
            countingVO.setShipmentName(shipmentCache.translate(countingVO.getShipmentCode()));
        }
        CountingItemDTO countingItemDTO = new CountingItemDTO();
        countingItemDTO.setCountingCode(code);
        countingItemDTO.setPageNum(pageNum);
        countingItemDTO.setPageSize(pageSize);
        countingItemDTO.setGroupCode(groupCode);
        CountingItemVO countingItemVO = countingItemService.queryListSum(countingItemDTO);
        //获取盘点单明细信息
        List<CountingItemVO> countingItemList = countingItemService.queryList(countingItemDTO);
        countingVO.setCountingItemList(countingItemList);


        Page returnPage = new Page(countingItemDTO.getPageNum(), countingItemDTO.getPageSize());
        returnPage.setRecords(countingItemList);
        returnPage.setTotal(countingItemVO.getTotal());
        returnPage.setSumObject(countingItemVO);

        countingVO.setReturnPage(returnPage);
        return countingVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean remove(List<String> codes) {
        //遍历删除盘点单明细
        codes.forEach(code -> countingItemService.remove(new QueryWrapper<CountingItem>().lambda().eq(CountingItem::getCountingCode, code).eq(CountingItem::getGroupCode,UserUtil.getBranchCode())));
        //删除盘点单
        return super.remove(new QueryWrapper<Counting>().lambda().in(Counting::getCode, codes).eq(Counting::getGroupCode,UserUtil.getBranchCode()));
    }

    /**
     * 更新盘点单状态
     *
     * @param counting
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateStatusByCode(Counting counting) {
        List<CountingItem> countingItemList = counting.getCountingItemList();
        if (CollUtil.isEmpty(countingItemList)) {
            throw new ServiceException("盘点登记明细为空，不可提交!");
        }
        String countingCode = countingItemList.get(0).getCountingCode();
        List<CountingRegister> countingRegisterList = counting.getCountingItemList().stream().map(item -> {
            CountingRegister countingRegister = new CountingRegister();
            countingRegister.setCode(IdUtil.simpleUUID());
            countingRegister.setCountingCode(countingCode);
            countingRegister.setCountingItemCode(item.getCode());
            countingRegister.setInventoryCode(item.getInventoryCode());
            countingRegister.setCreatedBy(UserUtil.getCode());
            countingRegister.setGmtCreated(LocalDateTime.now());
            countingRegister.setCountingQuantity(item.getCountingQuantity());
            countingRegister.setInventoryQuantity(item.getQuantity());
            return countingRegister;
        }).collect(Collectors.toList());
        countingRegisterService.remove(new QueryWrapper<CountingRegister>().lambda().eq(CountingRegister::getCountingCode, counting.getCode()).eq(CountingRegister::getGroupCode,UserUtil.getBranchCode()));
        countingRegisterService.saveBatch(countingRegisterList);

        return baseMapper.update(counting, new QueryWrapper<Counting>().lambda().eq(Counting::getCode, counting.getCode()).eq(Counting::getGroupCode,UserUtil.getBranchCode()));
    }

    /**
     * 盘点登记 确认
     *
     * @param counting    盘点单
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int confirm(Counting counting) {
        String countingCode = counting.getCode();
        String groupCode = UserUtil.getBranchCode();
        int status = super.count(new QueryWrapper<Counting>().lambda().eq(Counting::getCode, counting.getCode())
                .eq(Counting::getGroupCode,UserUtil.getBranchCode())
                .in(Counting::getStatus, CountingStatusEnum.WAIT_AUDIT, CountingStatusEnum.AUDIT));
        if (status > 0) {
            log.error("盘点单【{}】不能重复提交", countingCode);
            throw new ServiceException("盘点单不能重复提交!");
        }
        List<String> deleteCodes = counting.getDeleteCodes();
        if (IterUtil.isNotEmpty(deleteCodes)) {
            countingRegisterService.remove(new QueryWrapper<CountingRegister>().lambda().in(CountingRegister::getCode, deleteCodes).eq(CountingRegister::getGroupCode,UserUtil.getBranchCode()));
        }

        List<CountingRegister> countingRegisterList = counting.getCountingRegisterList();
        if (CollUtil.isNotEmpty(countingRegisterList)) {
            long count = countingRegisterList.stream().filter(item -> ObjectUtil.isNull(item.getCountingQuantity())).count();
            if (count > 0) {
                throw new ServiceException("盘点登记有盘点数量为空的明细，不可提交!");
            }
            makeCountingRegister(countingRegisterList, countingCode);
            countingRegisterService.saveOrUpdateBatch(counting.getCountingRegisterList());
        }

        boolean flag = addDifference(counting);
        if (flag) {
            //盘点登记确认后状态为待审核，生成差异单
            counting.setStatus(CountingStatusEnum.WAIT_AUDIT.getValue());
        } else {
            //更新主单、主单明细、主单登记状态为已审核
            counting.setStatus(CountingStatusEnum.AUDIT.getValue());
            countingItemService.update(new LambdaUpdateWrapper<CountingItem>()
                    .eq(CountingItem::getCountingCode, countingCode)
                    .eq(CountingItem::getGroupCode,groupCode)
                    .set(CountingItem::getStatus, CountingStatusEnum.AUDIT.getValue()));

            countingRegisterService.update(new LambdaUpdateWrapper<CountingRegister>()
                    .eq(CountingRegister::getCountingCode, countingCode)
                    .eq(CountingRegister::getGroupCode,groupCode)
                    .set(CountingRegister::getStatus, CountingStatusEnum.AUDIT.getValue()));

            //根据盘点数量更新库存
            List<CountingRegister> countingRegisters = countingRegisterService.list(new LambdaQueryWrapper<CountingRegister>()
                    .eq(CountingRegister::getCountingCode, countingCode)
                    .eq(CountingRegister::getGroupCode, groupCode));

            countingRegisters.forEach(r->{
                if(StrUtil.isNotBlank(r.getInventoryCode())){
                    inventoryService.update(new UpdateWrapper<Inventory>().lambda()
                            .eq(Inventory::getCode,r.getInventoryCode())
                            .set(Inventory::getQuantity,r.getCountingQuantity())
                    );
                    // 记录库存变动日志
                    iInventoryRecordService.insertRecord(r.getInventoryCode(), r.getCountingCode(), r.getCountingQuantity(), InventoryRecordTypeEnum.COUNTING.getValue());
                }
            });

        }
        wmsTaskMapper.update(null, new UpdateWrapper<WmsTask>().lambda().eq(WmsTask::getSourceCode, counting.getCode()).eq(WmsTask::getGroupCode,groupCode).set(WmsTask::getJobStatus, WmsTaskJobStatusEnum.COMPLETED));
        return baseMapper.update(counting, new QueryWrapper<Counting>().lambda().eq(Counting::getCode, counting.getCode()).eq(Counting::getGroupCode,groupCode));
    }



    /**
     * 根据盘点明细  生成差异单
     *
     * @param counting
     */
    public boolean addDifference(Counting counting) {
        List<CountingRegister> countingRegisterList = countingRegisterService.list(new QueryWrapper<CountingRegister>().lambda()
                .eq(CountingRegister::getGroupCode,UserUtil.getBranchCode())
                .eq(CountingRegister::getCountingCode, counting.getCode())
        );
        List<CountingRegister> countingRegisters = countingRegisterList.stream().filter(item -> item.getCountingQuantity().compareTo(item.getInventoryQuantity()) != 0).collect(Collectors.toList());
        if (IterUtil.isNotEmpty(countingRegisters)) {
            Difference difference = new Difference();
            BeanUtils.copyProperties(counting, difference);
            difference.setCode(OrderIdGeneratorUtil.generatorOrderId(OrderIdGeneratorUtil.OrderTypeEnum.CY, counting.getShipmentCode(),UserUtil.getBranchCode()));
            difference.setCountingCode(counting.getCode());
            difference.setWarehouseCode(counting.getWarehouseCode());
            difference.setStatus("0");
            iDifferenceService.save(difference);

            List<DifferenceItem> differenceItemList = new ArrayList<>();
            for (CountingRegister countingRegister : countingRegisters) {
                DifferenceItem differenceItem = new DifferenceItem();
                BeanUtils.copyProperties(countingRegister, differenceItem);
                differenceItem.setDifferenceCode(difference.getCode());
                differenceItem.setCode(IdUtil.simpleUUID());
                BigDecimal number = countingRegister.getCountingQuantity().subtract(countingRegister.getInventoryQuantity());
                differenceItem.setDifferenceQuantity(number);
                differenceItem.setType("0");
                if (number.compareTo(BigDecimal.ZERO) < 0) {
                    differenceItem.setType("1");
                }
                differenceItem.setInventoryQuantity(countingRegister.getInventoryQuantity());
                differenceItem.setQuantity(countingRegister.getCountingQuantity());
                differenceItem.setCreatedBy(countingRegister.getCreatedBy());
                differenceItem.setGmtCreated(countingRegister.getGmtCreated());
                differenceItem.setGmtModified(countingRegister.getGmtModified());
                differenceItemList.add(differenceItem);
            }

            iDifferenceItemService.saveBatch(differenceItemList);

            return true;
        }
        return false;
    }

    /**
     * 更新盘点单状态
     *
     * @param counting    盘点单
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateRegisterByCode(Counting counting) {
        int status = super.count(new QueryWrapper<Counting>().lambda().eq(Counting::getCode, counting.getCode()).eq(Counting::getGroupCode,UserUtil.getBranchCode()).in(Counting::getStatus, CountingStatusEnum.WAIT_AUDIT, CountingStatusEnum.AUDIT));
        if (status > 0) {
            log.error("盘点单【{}】已提交", counting.getCode());
            throw new ServiceException("盘点单已提交不能保存!");
        }
        List<String> deleteCodes = counting.getDeleteCodes();
        if (IterUtil.isNotEmpty(deleteCodes)) {
            countingRegisterService.remove(new QueryWrapper<CountingRegister>().lambda().in(CountingRegister::getCode, deleteCodes).eq(CountingRegister::getGroupCode,UserUtil.getBranchCode()));
        }


        List<CountingRegister> countingRegisterList = counting.getCountingRegisterList();
        if (CollUtil.isNotEmpty(countingRegisterList)) {
            long count = countingRegisterList.stream().filter(item -> ObjectUtil.isNull(item.getCountingQuantity())).count();
            if (count > 0) {
                throw new ServiceException("盘点登记有盘点数量为空的明细，不可提交!");
            }
            makeCountingRegister(countingRegisterList, counting.getCode());
            countingRegisterService.saveOrUpdateBatch(countingRegisterList);
        }

        //更新盘点明细状态为待审核
        countingItemService.update(new UpdateWrapper<CountingItem>().lambda()
                .eq(CountingItem::getGroupCode,UserUtil.getBranchCode())
                .eq(CountingItem::getCountingCode, counting.getCode())
                .set(CountingItem::getStatus, CountingStatusEnum.WAIT_AUDIT)
        );
        counting.setStatus(CountingStatusEnum.COUNTING.getValue());
        return baseMapper.update(counting, new QueryWrapper<Counting>().lambda().eq(Counting::getCode, counting.getCode()).eq(Counting::getGroupCode,UserUtil.getBranchCode()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int invalid(String code) {
        Counting counting = new Counting();
        counting.setCode(code);
        counting.setStatus(CountingStatusEnum.INVALID.getValue());
        return baseMapper.update(counting, new QueryWrapper<Counting>().lambda().eq(Counting::getCode, counting.getCode()).eq(Counting::getGroupCode,UserUtil.getBranchCode()));
    }

    @Override
    public List<CountingItemVO> queryTaskDetailByCode(CountingDTO countingDTO) {
        return baseMapper.queryTaskDetailByCode(countingDTO);
    }

    /**
     * 更新下发状态
     *
     * @param code 盘点单标识
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public void updateIssueStatus(String code,String groupCode) {
        this.update(new UpdateWrapper<Counting>().lambda().eq(Counting::getCode, code)
                .eq(Counting::getGroupCode,groupCode)
                .set(Counting::getIssue, IssueStatusEnum.ISSUED));
    }

    @Override
    public CountingVO registerDetail(String code,int pageNum,int pageSize) {
        String groupCode = UserUtil.getBranchCode();
        Counting counting = getOne(new QueryWrapper<Counting>().lambda().eq(Counting::getCode, code).eq(Counting::getGroupCode,groupCode));
        if (null == counting) {
            log.error("盘点单【{}】不存在", code);
            throw new ServiceException("盘点单: " + code + "不存在!");
        }

        CountingVO countingVO = new CountingVO();
        BeanUtils.copyProperties(counting, countingVO);
        countingVO.setGroupCode(UserUtil.getBranchCode());
        countingVO.setGroupName(partyGroupCache.translate(countingVO.getGroupCode()));

        if(StrUtil.isNotBlank(countingVO.getLocation())){
            Location location = iLocationService.getOne(new LambdaQueryWrapper<Location>().eq(Location::getCode,countingVO.getLocation()).eq(Location::getGroupCode,UserUtil.getBranchCode()));
            if(null!=location) {
                countingVO.setLocationName(location.getSerialNumber());
            }
        }
        if(StrUtil.isNotBlank(countingVO.getShipmentCode())){

            countingVO.setShipmentName(shipmentCache.translate(countingVO.getShipmentCode()));
        }
        CountingRegisterDTO countingRegisterDTO = new CountingRegisterDTO();
        countingRegisterDTO.setCountingCode(code);
        countingRegisterDTO.setPageNum(pageNum);
        countingRegisterDTO.setPageSize(pageSize);
        countingRegisterDTO.setGroupCode(groupCode);
        CountingRegisterVO countingRegisterVO = countingRegisterService.queryListSum(countingRegisterDTO);

        List<CountingRegisterVO> countingRegisterVOList = countingRegisterService.queryList(countingRegisterDTO);

        if (IterUtil.isNotEmpty(countingRegisterVOList)) {
            countingRegisterVOList.forEach(r -> {
                // 对补登的确认单添加一些必要信息
                if (StrUtil.isBlank(r.getCountingItemCode()) || 1 == r.getRegisterType()) {
                    String shipmentCode = r.getShipmentCode();
                    String goodsCode = r.getGoodsCode();
                    if (StrUtil.isNotBlank(shipmentCode)) {
                        List<InventoryStatus> inventoryStatuses = iInventoryStatusService.list(new QueryWrapper<InventoryStatus>().lambda().eq(InventoryStatus::getShipmentCode, shipmentCode).eq(InventoryStatus::getStatus, "0").eq(InventoryStatus::getGroupCode,UserUtil.getBranchCode()));
                        if (IterUtil.isNotEmpty(inventoryStatuses)) {
                            r.setInventoryStatuses(inventoryStatuses);
                        }
                    }

                    if (StrUtil.isNotBlank(goodsCode)) {
                        Map<String, Object> goodsMap = goodsCache.get(goodsCode);
                        if (MapUtil.isNotEmpty(goodsMap)) {
                            Goods goods = BeanUtil.mapToBean(goodsMap, Goods.class, false);
                            r.setBatchRule(goods.getBatchRule());
                        }
                    }
                }
                r.setStatusName(CountingRegisterStatusEnum.translate(r.getStatus()));
            });
        }

        Page returnPage = new Page(countingRegisterDTO.getPageNum(), countingRegisterDTO.getPageSize());
        returnPage.setRecords(countingRegisterVOList);
        returnPage.setTotal(countingRegisterVO.getTotal());
        returnPage.setSumObject(countingRegisterVO);

        countingVO.setReturnPage(returnPage);
        countingVO.setCountingRegisterList(countingRegisterVOList);
        return countingVO;
    }

    /**
     * 保存盘点单明细
     *
     * @param entity
     */
    private void saveItem(Counting entity) {
        String code = UserUtil.getCode();
        String createdName = partyCache.translate(code);
/*        entity.getCountingItemList().forEach(r -> {
            r.setCode(IdUtil.simpleUUID());
            r.setCountingCode(entity.getCode());
            r.setStatus(CountingStatusEnum.WAIT_COUNT.getValue());
            //r.setShipmentName(shipmentCache.translate(r.getShipmentCode()));
            //Map<String, Object> goodsMap = goodsCache.get(r.getGoodsCode());
            //r.setSpec((String) goodsMap.get("spec"));
            //r.setGoodsUnitName(r.getUnitName());
            //r.setLocationName(locationCache.translate(r.getLocation()));
            r.setCreatedBy(code);
            r.setModifiedBy(code);
            r.setCreatedName(createdName);
            r.setModifiedName(createdName);
            r.setGmtCreated(LocalDateTime.now());
        });
        //批量保存盘点单明细
        countingItemService.saveBatch(entity.getCountingItemList());*/
        countingItemService.insertBatch(entity.getCode(), code,createdName,entity.getWarehouseCode(),
                entity.getGroupCode(),entity.getLocation(),entity.getShipmentCode(),entity.getOpQuantity());
    }


    /**
     * 构造翻译盘点登记信息
     *
     * @param countingRegisterList
     * @param countingCode
     */
    private void makeCountingRegister(List<CountingRegister> countingRegisterList, String countingCode) {
        String code = UserUtil.getCode();
        String groupCode = UserUtil.getBranchCode();
        String createdName = partyCache.translate(code);
        countingRegisterList.forEach(item -> {
            if (StrUtil.isBlank(item.getCode())) {
                item.setCode(IdUtil.simpleUUID());
                item.setRegisterType(1);
                item.setCreatedBy(code);
                item.setCreatedName(createdName);

                if (StrUtil.isBlank(item.getGoodsCode())) {
                    log.error("盘点登记补登商品【{}】不能为空!", item.getGoodsCode());
                    throw new ServiceException("盘点登记补登商品不能为空!");
                }
                if (StrUtil.isBlank(item.getLocation())) {
                    log.error("盘点登记补登商品【{}】库位【{}】不能为空!", item.getGoodsCode(), item.getLocation());
                    throw new ServiceException("盘点登记补登商品库位不能为空!");
                }

                Map<String, Object> goodsMap = goodsCache.get(item.getGoodsCode());
                if (MapUtil.isEmpty(goodsMap)) {
                    log.error("盘点登记补登商品【{}】不能为空!", item.getGoodsCode());
                    throw new ServiceException("盘点登记补登商品不能为空!");
                }
                Map<String, Object> locationMap = locationCache.get(item.getLocation());
                if (MapUtil.isEmpty(locationMap)) {
                    log.error("盘点登记补登商品【{}】库位【{}】不能为空!", item.getGoodsCode(), item.getLocation());
                    throw new ServiceException("盘点登记补登商品库位不能为空!");
                }


                Goods goods = BeanUtil.mapToBean(goodsMap, Goods.class, false);
                item.setGoodCode(goods.getGoodCode());
                item.setGoodsName(goods.getName());
                item.setGoodsBarCode(goods.getBarCode());
                item.setGoodsUnit(goods.getUnitCode());
                item.setGoodsUnitName(goods.getBasicUnitName());
                item.setSpec(goods.getSpec());

                Location location = BeanUtil.mapToBean(locationMap, Location.class, false);
                item.setLocationName(location.getSerialNumber());
                item.setWarehouseSpaceCode(location.getSpaceCode());
                item.setWarehouseSpaceName(location.getWarehouseSpaceName());
            }
            item.setGroupCode(groupCode);
            item.setCountingCode(countingCode);
            item.setStatus(CountingStatusEnum.WAIT_AUDIT.getValue());
            item.setModifiedBy(code);
            item.setModifiedName(createdName);
        });
    }


}
